package servlet;

import util.HttpProtocolUtil;
import util.ResourceUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 封装Response
 * <p>
 * 该对象提供核心方法，输出html静态资源
 */
public class Response {
    private OutputStream outputStream;

    public Response() {
    }

    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    public void output(String content) throws IOException {
        outputStream.write(content.getBytes());
    }

    public void outputHtml(String path) throws IOException {
        //根据路径去读取Html的绝对路径 并 输出
//        String absoluteResourcePath = ResourceUtil.getAbsolutePath(path);
        //根据配置的路径钱输出静态文件
//        path.replace("\\\\", "/") + path
        //输出静态资源
        File file = new File(path);
        if (file.exists() && file.isFile()) {
            //输出静态资源
            ResourceUtil.outputStaticeResource(new FileInputStream(file), outputStream);
        } else {
            //输出404
            output(HttpProtocolUtil.getHttpHeader404());
        }
    }
}
